package com.cloud.class04.resp;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    public static void main(String[] args) {
        // 创建一个具有4个许可的Semaphore
        Semaphore semaphore = new Semaphore(4);

        // 创建一个固定大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(8);

        // 向线程池中提交8个任务
        for (int i = 0; i < 8; i++) {
            executorService.submit(new Task(semaphore, i));
        }

        // 关闭线程池
        executorService.shutdown();
    }

    static class Task implements Runnable {
        private Semaphore semaphore;
        private int id;

        public Task(Semaphore semaphore, int id) {
            this.semaphore = semaphore;
            this.id = id;
        }

        @Override
        public void run() {
            try {
                // 获取许可
                semaphore.acquire();
                System.out.println("线程 " + Thread.currentThread().getName() + " 获取到一辆汽车");
                Thread.sleep(2000);
                System.out.println("线程 " + Thread.currentThread().getName() + " 释放一辆汽车");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
